import { filterEmptyByObject } from "@/tools/common"
import { reactive } from "vue"

const useTable = (ajaxFunc, initColumns = [], initOperate = [], initSearchParams = []) => {

  const state = reactive({
    params: {},
    selectedRowKeys: [],
    visibleSave: false,
    visibleEdit: false,
    visibleInfo: false,
    importVisible: false,
    recordEdit: {},
    recordInfo: {},
    searchParams: initSearchParams,
    columns: initColumns,
    operate: initOperate
  })

  const pagination = {
    pageNum: 1,
    pageSize: 10,
  }

  const search = params => {
    state.param = {
      ...state.params,
      ...filterEmptyByObject(params)
    }
    const rangeTimeItem = initSearchParams.find(v => v.type === 'rangeTime')
    if (rangeTimeItem && rangeTimeItem.keys) {
      state.param[rangeTimeItem.keys[0]] = state.param[rangeTimeItem.key] ? state.param[rangeTimeItem.key][0] : undefined
      state.param[rangeTimeItem.keys[1]] = state.param[rangeTimeItem.key] ? state.param[rangeTimeItem.key][1] : undefined
      delete state.param[rangeTimeItem.key]
    }
  }

  const fetch = async param => {
    const response = await ajaxFunc(param)

    if (response.code === 500) {
      return {
        data: [],
        total: 0
      }
    }

    return {
      data: response.data.record,
      total: response.data.total
    }
  }

  const updateSearchParams = (searchParams = []) => {
    state.searchParams = searchParams
  }

  const updateColumns = (columnsProps = []) => {
    state.columns = columnsProps
  }

  const updateOperate = (operateProps = []) => {
    state.operate = operateProps
  }

  return {
    state,
    pagination,
    search,
    fetch,
    updateSearchParams,
    updateColumns,
    updateOperate
  }
}

export default useTable
